package com.douhl.common.utils;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.poi.util.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * create time 2020/4/25 9:26
 *
 * @author lining
 * @version 0.0.1
 * update:
 * Copyright © 2017 - 2020 Jiansu Dingye.All rights reserved.
 * Company Jiansu Dingye
 */

@Component
public class MongodbUtils {
    @Autowired
    private GridFsTemplate gridfsTemplate;
    @Autowired
    private MongoDbFactory mongoDbFactory;

    public static MongodbUtils mongodbUtils;

    private  GridFSBucket bucket;

    @PostConstruct
    public void init(){
        mongodbUtils = this;
        mongodbUtils.gridfsTemplate = this.gridfsTemplate;
        mongodbUtils.mongoDbFactory = this.mongoDbFactory;
        mongodbUtils.bucket = GridFSBuckets.create( mongodbUtils.mongoDbFactory.getDb());
    }

    /**
     * 根据id查询文件
     */
    public static GridFSFile findFileById(Object id) throws Exception {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        return mongodbUtils.gridfsTemplate.findOne(query);
    }

    /**
     * 保存文件
     *
     * @param file
     */
    public static String saveFile(MultipartFile file) throws IOException {
        ObjectId id = mongodbUtils.gridfsTemplate.store(file.getInputStream(), UUID.randomUUID().toString().replaceAll("-", "") + ".jpg", file.getContentType());
        return id.toString();
    }

    /**
     * 根据id删除文件
     */
    public static void deleteFileById(Object id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        mongodbUtils.gridfsTemplate.delete(query);
    }

    public static byte[] downloadFile(String objectId) throws Exception {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(objectId));
        GridFSFile gridFSFile = mongodbUtils.gridfsTemplate.findOne(query);
        GridFSDownloadStream in = mongodbUtils.bucket.openDownloadStream(gridFSFile.getObjectId());
        GridFsResource resource = new GridFsResource(gridFSFile, in);
        InputStream inputStream = resource.getInputStream();
        return IOUtils.toByteArray(inputStream);
    }

}
